package com.onlineMIS.ORM.DAO.headQ.custMgmt;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.onlineMIS.ORM.DAO.BaseDAO;
import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.HeadQEntityTagDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.HeadQTagDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.HeadQTagGroupDaoImpl;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTag;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTagGroup;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadqEntityTag;
import com.onlineMIS.ORM.entity.headQ.custMgmt.HeadQCust;
import com.onlineMIS.ORM.entity.headQ.supplier.supplierMgmt.HeadQSupplier;
import com.onlineMIS.action.headQ.custMgmt.HeadQCustMgmtFormBean;
import com.onlineMIS.action.headQ.report.HeadQReportFormBean;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;

@Repository
public class HeadQCustDaoImpl extends BaseDAO<HeadQCust>{
	
	
	@Autowired
	private HeadQEntityTagDaoImpl headQEntityTagDaoImpl;
	@Autowired
	private HeadQTagDaoImpl headQTagDaoImpl;
	@Autowired
	private HeadQTagGroupDaoImpl headQTagGroupDaoImpl;
	

	public List<HeadQCust> getCustByPinyin(String pinyin, int status) {
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQCust.class);
		criteria.add(Restrictions.like("pinyin", "%"+pinyin +"%"));
		criteria.add(Restrictions.eq("status", status));
		
		return this.getByCritera(criteria, true);
	}

	public HeadQCust getAllCustObj() {
		HeadQCust cust = new HeadQCust();
		cust.setId(0);
		cust.setName("所有客户");
		return cust;
	}

	/**
	 * 根据客户标签获取客户信息
	 */
	public List<Integer> getCustIds(HeadQReportFormBean formBean) {
		/**
		 * 
		 * 客户标签条件为：A-一组标签, B-二组标签, C-三组标签 ,D-四组标签
		 * 
		 */
		List<Integer> clientIds = new ArrayList<Integer>();
		try {
			String hql = "select s1.entityId,count(*) from HeadqEntityTag s1 where (";
			int count = 0;

			if (formBean.getTagLevelOne() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelOne();
				count ++;
			}
			if (formBean.getTagLevelOne() == null && formBean.getTagLevelTwo() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelTwo();
				count ++;
			} else if (formBean.getTagLevelOne() != null && formBean.getTagLevelTwo() != null) {
				hql += " or s1.tagId =" + formBean.getTagLevelTwo();
				count ++;
			}

			if ((formBean.getTagLevelOne() == null && formBean.getTagLevelTwo() == null ) && formBean.getTagLevelThree() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelThree();
				count ++;
			} else if ((formBean.getTagLevelOne() != null || formBean.getTagLevelTwo() != null ) && formBean.getTagLevelThree() != null) {
				hql += " or s1.tagId =" + formBean.getTagLevelThree();
				count ++;
			}

			if ((formBean.getTagLevelOne() == null && formBean.getTagLevelTwo() == null && formBean.getTagLevelThree() == null) && formBean.getTagLevelFour() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelFour();
				count ++;
			} else if ((formBean.getTagLevelOne() != null || formBean.getTagLevelTwo() != null || formBean.getTagLevelThree() != null) && formBean.getTagLevelFour() != null) {
				hql += " or s1.tagId =" + formBean.getTagLevelFour();
				count ++;
			}
			if (count !=0) {
				hql += ") group by s1.entityId  having count(*) = " + count;
				List<Object> values = this.executeHQLSelect(hql, null, null, true);
				if (values.size() != 0) {
					for (Object record : values) {
						Object[] recordResult = (Object[])record;
						clientIds.add(Common_util.getInt(recordResult[0]));
					}
				}	
			}
						
		} catch (Exception e) {
			loggerLocal.error(e);
		}
		return clientIds;
	}

	/**
	 * 批量添加标签
	 * @param ids
	 * @param tagId
	 * @param type
	 * @return
	 */
	public Response saveBatchEntityTags(int[] ids, int tagId) {
		Response response = new Response();
		HeadQTag headQTag = headQTagDaoImpl.get(tagId, true);
		// 根据分组id获取分组对象
		HeadQTagGroup hGroup = headQTagGroupDaoImpl.get(headQTag.getGroupId().getId(), true);
		if (ids.length > 0) {
			// 校验所有客户
			for (int entityId : ids) {
				HeadQCust cust = this.get(entityId, true);
				HeadqEntityTag entityTag = headQEntityTagDaoImpl.selectEntityTag(entityId, tagId);
				if (entityTag != null) {
					response.setSuccess("客户: " + cust.getName() + "已有 " + hGroup.getGroupName() + "标签,请勿重复添加!");
					response.setReturnCode(Response.SUCCESS);
					return response;
				} else {
					// 校验客户标签
					Boolean result = headQEntityTagDaoImpl.isExistence(entityId, tagId);
					if (result) {
						response.setSuccess("客户: " + cust.getName() + "  已有" + hGroup.getGroupName() + "标签,请勿重复添加!");
						response.setReturnCode(Response.SUCCESS);
						return response;
					} else {
						break;
					}
				}
			}

		}
		// 批量添加客户标签
		this.saveBeachEntity(ids, tagId);
		response.setSuccess("客户标签添加成功!");
		response.setReturnCode(Response.SUCCESS);
		return response;
	}
	
	
	
	/**
	 * 批量添加客户标签
	 * @param ids
	 * @param tagId
	 */
	private void saveBeachEntity(int[] ids, int tagId) {
		if (ids.length != 0) {
			for (int entityId : ids) {
				HeadqEntityTag entity = new HeadqEntityTag();
				entity.setEntityId(entityId);
				entity.setTagId(tagId);
				headQEntityTagDaoImpl.save(entity,true);
			}
		}
		
	}
	
	/**
	 * 批量删除客户标签
	 * @param ids
	 * @param tagId
	 */
	private void deleteBeachEntity(int[] ids, int tagId) {
		if (ids.length != 0) {
			for (int entityId : ids) {
				HeadqEntityTag entity = headQEntityTagDaoImpl.selectEntityTag(entityId, tagId);
				headQEntityTagDaoImpl.delete(entity,true);
			}
		}
		
	}

	/**
	 * 批量删除客户标签
	 * @param ids
	 * @param tagId
	 * @return
	 */
	public Response deleteBatchEntityTags(int[] ids, int tagId) {
		Response response = new Response();
		if (ids.length > 0) {
			//校验所有客户
			for (int entityId : ids) {		
				HeadQCust cust = this.get(entityId, true);
				HeadQTag headQTag = headQTagDaoImpl.get(tagId, true);
				HeadqEntityTag entityTag = headQEntityTagDaoImpl.selectEntityTag(entityId, tagId);					
				  if (entityTag == null) {
					response.setSuccess("标签删除失败, 客户: "+cust.getName() +"未包含:【 "+headQTag.getTagName()+" 】标签信息!");
					response.setReturnCode(Response.SUCCESS);
					return response;
				}
			}
			// 批量删除客户标签客户
			this.deleteBeachEntity(ids, tagId);
			response.setSuccess("客户标签删除成功!");
			response.setReturnCode(Response.SUCCESS);
		}
		return response;
	}

	/**
	 * 根据客户名称模糊查询客户IDS
	 * @param custName
	 * @return
	 */
	public List<Integer> selectIdsByName(String custName) {
		List<Integer> ids = new ArrayList<Integer>();
		DetachedCriteria custCriteria = DetachedCriteria.forClass(HeadQCust.class);
		if (custName != null && custName != "") {
			Pattern pattern = Pattern.compile("[A-Za-z]*");
			Matcher isNum = pattern.matcher(custName);
			
			if (isNum.matches() ) {
				custCriteria.add(Restrictions.like("pinyin", custName, MatchMode.ANYWHERE));
			}	else {
				custCriteria.add(Restrictions.like("name", custName, MatchMode.ANYWHERE));
			}
		}		
		List<HeadQCust> custs =  this.getByCritera(custCriteria,true);
		if (custs.size() !=0) {
			for (HeadQCust headQCust : custs) {
				ids.add(headQCust.getId());
			}
		}
		return ids;
	}

	public List<Integer> getCusts(HeadQCustMgmtFormBean formBean){
		List<Integer> clientIds = new ArrayList<Integer>();
		try {
			String hql = "select s1.entityId,count(*) from HeadqEntityTag s1 where (";
			int count = 0;

			if (formBean.getTagLevelOne() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelOne();
				count ++;
			}
			if (formBean.getTagLevelOne() == null && formBean.getTagLevelTwo() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelTwo();
				count ++;
			} else if (formBean.getTagLevelOne() != null && formBean.getTagLevelTwo() != null) {
				hql += " or s1.tagId =" + formBean.getTagLevelTwo();
				count ++;
			}

			if ((formBean.getTagLevelOne() == null && formBean.getTagLevelTwo() == null ) && formBean.getTagLevelThree() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelThree();
				count ++;
			} else if ((formBean.getTagLevelOne() != null || formBean.getTagLevelTwo() != null ) && formBean.getTagLevelThree() != null) {
				hql += " or s1.tagId =" + formBean.getTagLevelThree();
				count ++;
			}

			if ((formBean.getTagLevelOne() == null && formBean.getTagLevelTwo() == null && formBean.getTagLevelThree() == null) && formBean.getTagLevelFour() != null) {
				hql += "s1.tagId =" + formBean.getTagLevelFour();
				count ++;
			} else if ((formBean.getTagLevelOne() != null || formBean.getTagLevelTwo() != null || formBean.getTagLevelThree() != null) && formBean.getTagLevelFour() != null) {
				hql += " or s1.tagId =" + formBean.getTagLevelFour();
				count ++;
			}
			if (count !=0) {
				hql += ") group by s1.entityId  having count(*) = " + count;
				List<Object> values = this.executeHQLSelect(hql, null, null, true);
				if (values.size() != 0) {
					for (Object record : values) {
						Object[] recordResult = (Object[])record;
						clientIds.add(Common_util.getInt(recordResult[0]));
					}
				}	
			}
						
		} catch (Exception e) {
			loggerLocal.error(e);
		}
		return clientIds;
	}

	public List<HeadQCust> selectCusts() {
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQCust.class);
		criteria.add(Restrictions.eq("status", HeadQCust.CustStatusEnum.GOOD.getKey()));

		List<HeadQCust> custs = getByCritera(criteria, true);
		return custs;
	}

	/**
	 * 根据客户ids查询客户信息
	 * @param custIds
	 * @return
	 */
	public List<HeadQCust> selectCustsByIds(List<Integer> custIds) {
		List<HeadQCust> list = new ArrayList<HeadQCust>();
		DetachedCriteria custCriteria = DetachedCriteria.forClass(HeadQCust.class);		
		if (custIds.size()>0) {
			custCriteria.add(Restrictions.in("id", custIds));
		}	
		list = this.getByCritera(custCriteria, true);
		return list;
	}

	/**
	 * 根据客户名称模糊查询客户IDS
	 * @param custName
	 * @return
	 */
	public List<HeadQCust> selectCusts(String custName) {
		DetachedCriteria custCriteria = DetachedCriteria.forClass(HeadQCust.class);
		if (custName != null && custName != "") {
			Pattern pattern = Pattern.compile("[A-Za-z]*");
			Matcher isNum = pattern.matcher(custName);
			
			if (isNum.matches() ) {
				custCriteria.add(Restrictions.like("pinyin", custName, MatchMode.ANYWHERE));
			}	else {
				custCriteria.add(Restrictions.like("name", custName, MatchMode.ANYWHERE));
			}
		}		
		List<HeadQCust> custs =  this.getByCritera(custCriteria,true);
		return custs;
	}
}
